package com.qf.barrier;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.barriers.DistributedDoubleBarrier;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class CuratorBarrier {
    private static final String ZKADDR = "10.9.12.200:8601,10.9.12.200:8602,10.9.12.200:8603";
    private static CountDownLatch countDownLatch = new CountDownLatch(1);//用作阻塞的, 1 的意思是只需有一个地方执行了放行就放行所有阻塞的地方


    public static void main(String[] args) throws Exception {



        for (int i = 0; i < 10; i++) {
            new Thread(){
                @Override
                public void run() {
                    try {
                        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                                .connectString(ZKADDR)
                                .connectionTimeoutMs(5000)
                                .retryPolicy(new ExponentialBackoffRetry(1000, 5))
                                .build();
//                    开始连接
                        curatorFramework.start();

                        DistributedDoubleBarrier doubleBarrier=new DistributedDoubleBarrier(curatorFramework, "/www", 10);

                        Thread.sleep(new Random().nextInt(3)*1000);
//                      准备进入游戏
                        System.err.println("大家都准备好了"+Thread.currentThread().getName());
                        doubleBarrier.enter();
                        System.out.println("开始游戏了");

                        Thread.sleep(new Random().nextInt(3)*1000);
                        System.err.println("不想玩了"+Thread.currentThread().getName());

                        doubleBarrier.leave();
                        System.out.println("退出游戏");

                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }
            }.start();
        }
        System.in.read();


    }

}
